package com.baymax.study.tuLing.netty.d1_base;

import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;

/**
 * @author baymax
 * @since 2025-06-27
 */
@Slf4j
public class Demo3 {
    public static final int PORT = 60001;

    static class NettyServer {
        public static void main(String[] args) throws InterruptedException {
            EventLoopGroup boss = new NioEventLoopGroup(1); // 只负责accept请求
            EventLoopGroup worker = new NioEventLoopGroup(2); // 只负责处理读写
            ChannelFuture channelFuture = new ServerBootstrap().group(boss, worker)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) {
                        ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) {
                                ByteBuf buf = (ByteBuf) msg;
                                log.info("{}", buf.toString(StandardCharsets.UTF_8));
                            }
                        });
                    }
                })
                .bind(new InetSocketAddress(PORT));
            channelFuture.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    log.info("服务器启动完成");
                }
            });
            channelFuture.sync();
            Channel channel = channelFuture.channel();
            channel.closeFuture().sync();
            log.info("服务器已关闭");
        }
    }

    static class NettyClient {
        public static void main(String[] args) throws InterruptedException {
            NioEventLoopGroup group = new NioEventLoopGroup();
            ChannelFuture future = new Bootstrap().group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new StringEncoder(StandardCharsets.UTF_8));
                    }
                })
                .connect(new InetSocketAddress("127.0.0.1", PORT))
                .sync();
            Channel channel = future.channel();
            channel.writeAndFlush("hello, netty");
            channel.close(); // 异步关闭，关闭的顺序无法保证
            ChannelFuture closeFuture = channel.closeFuture();
            closeFuture.sync();
            log.info("发送完成，客户端已关闭"); // 这个无法关闭所有的线程，jvm还会运行
            group.shutdownGracefully(); // 优雅关闭所有线程
        }
    }

}
